package com.fzt.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzt.admin.common.biz.user.UserContext;
import com.fzt.admin.common.convention.exception.ClientException;
import com.fzt.admin.common.convention.exception.ServiceException;
import com.fzt.admin.common.convention.result.Result;
import com.fzt.admin.common.convention.result.Results;
import com.fzt.admin.dao.entity.UserDO;
import com.fzt.admin.dao.mapper.UserMapper;
import com.fzt.admin.dto.req.ShortLinkGroupSaveReqDTO;
import com.fzt.admin.dto.req.UserLoginReqDTO;
import com.fzt.admin.dto.req.UserRegisterDTO;
import com.fzt.admin.dto.req.UserUpdateReqDTO;
import com.fzt.admin.dto.resp.UserLoginRespDTO;
import com.fzt.admin.dto.resp.UserRespDTO;
import com.fzt.admin.service.GroupService;
import com.fzt.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.fzt.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.fzt.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.fzt.admin.common.enums.UserErrorCodeEnum.*;

@Service
@RequiredArgsConstructor //构造器注入
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;

    /*
    根据用户名查询用户
     */
    @Override
    public Result<UserRespDTO> getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> eq = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(eq);
        return Results.success(BeanUtil.copyProperties(userDO,UserRespDTO.class));
    }

    /*
    用户注册
     */
    @Override
    public void register(UserRegisterDTO userRegisterDTO) {

        if (!hasUsername(userRegisterDTO.getUsername())){
            //用户名已存在
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + userRegisterDTO.getUsername());
        try {
            if (lock.tryLock()){
                int count = baseMapper.insert(BeanUtil.copyProperties(userRegisterDTO, UserDO.class));
                if (count < 1){
                    throw new ClientException(USER_SAVE_ERROR);
                }
                userRegisterCachePenetrationBloomFilter.add(userRegisterDTO.getUsername());
                groupService.saveGroup(userRegisterDTO.getUsername(), new ShortLinkGroupSaveReqDTO("默认分组"));
                return;
            }
            throw new ClientException(USER_NAME_EXIST);
        }finally {
            lock.unlock();
        }

    }

    /*
    判断用户名是否存在
    存在返回false
     */
    @Override
    public Boolean hasUsername(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /*
    根据用户名修改用户
     */
    @Override
    public void updateByUsername(UserUpdateReqDTO userUpdateReqDTO) {
        if (!Objects.equals(UserContext.getUsername(),userUpdateReqDTO.getUsername())){
            throw new ClientException("非当前登入用户");
        }
        LambdaUpdateWrapper<UserDO> eq = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername,userUpdateReqDTO.getUsername());
        int count = baseMapper.update(BeanUtil.copyProperties(userUpdateReqDTO, UserDO.class), eq);
        if (count < 1) {
            throw new ServiceException(USER_UPDATE_ERROR);
        }
    }

    /*
    用户登入
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDO::getPassword, userLoginReqDTO.getPassword());
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            //用户不存在
            throw new ClientException(USER_NULL);
        }
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(USER_LOGIN_KEY + userDO.getUsername()))){
            throw new ClientException("用户已登入");
        }
        /*
        Hash
        key:login_用户名
        value:
            key:token
            value:用户信息
         */
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY+userDO.getUsername(),
                uuid,
                JSON.toJSONString(userDO));
        stringRedisTemplate.expire(USER_LOGIN_KEY+userDO.getUsername(), 30L, TimeUnit.DAYS);
        //stringRedisTemplate.opsForValue().set(uuid, JSON.toJSONString(userDO), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    /*
    检查用户是否登入
    @param token 用户登入token
     */
    @Override
    public Boolean checkLogin(String token, String username) {
        Object user = stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token);
        return user != null;

    }

    /*
    退出登入
     */
    @Override
    public void logout(String token, String username) {
        if (checkLogin(token,username)){
            stringRedisTemplate.opsForHash().delete(USER_LOGIN_KEY + username,token);
            return;
        }
        throw new ClientException("用户未登入");
    }
}
